<template>
      <el-select
        class="brandDropdownButton"
        v-model="brandId"
        filterable
        remote
        reserve-keyword
        placeholder="请输入品牌关键字"
        :remote-method="queryBrandList"
        @change="changeBrandId"
        :disabled="categoryId === 0"
      >
        <el-option
          v-for="item in brandOptions"
          :key="item.id"
          :label="item.name"
          :value="item.id">
        </el-option>
      </el-select>

</template>

<script>
import {listBrand} from "@/api/prod/brand";

export default {
  name: "brand-selection",
  props: {
    categoryId: {
      type: Number,
      default: null
    },
    sourceBrandId: {
      type: Number,
      default: null
    },
  },
  data() {
    return {
      isFirstInit: true, //是否第一次初始化时
      brandOptions: [],
      brandQuery: {
        pageNum: 1,
        pageSize: 50,
        name: "",
        categoryId: null,
        id: null
      },
      brandId: null
    }
  },
  methods: {
    changeBrandId(){
      // console.log(this.brandId)
      this.$emit('update:sourceBrandId', this.brandId);
    },
    queryBrandList(keywords) {
      this.brandQuery.name = keywords;

      if (!keywords) {
        this.brandQuery.name = "";
      }
      this.brandQuery.categoryId = this.categoryId
      listBrand(this.brandQuery).then(response => {
        this.brandOptions = response.rows.map(item => {
          return {
            id: item.id,
            name: item.name
          }
        })

        //关联品牌弹框, 删除关联品牌后, 可能已经原先在发布商品页面选择的品牌id, 不再存在与类目关联品牌列表中, 需要清空已选择的品牌
        if (this.brandId && !this.brandOptions.some(option => option.id === this.brandId)) {
          this.brandId = null;
          this.$emit('input', null);
          this.$modal.msgWarning("类目关联品牌列表已更新, 请重新选择品牌!");
        }
      })
    },
  },
  watch: {
    categoryId(val, oldVal) {
      // console.log(val, oldVal)
      if (val !== 0) {
        if (!this.isFirstInit){
          this.queryBrandList();
        }
      }
    },
    sourceBrandId: {
      deep: true,
      immediate: true, // 当 this.prodForm.brandId = null 时 也能监听到
      handler: function (val, oldVal) {
        this.brandId = val;

        //是否首次
        if (this.isFirstInit){
          this.isFirstInit = false;
          //是编辑商品的情况
          this.$nextTick(() =>{

            //在编辑商品时,created 里才有brandId
            if (this.brandId){
              //  确保编辑商品初始化时, 拿到的 brandOptions 中一定有 当前正在编辑的prod.brandId关联的 option
              this.brandQuery.id = this.brandId
              this.queryBrandList();
              //  确保初始化后, 后续用户输入关键字查找品牌时, brandQuery 只会根据 categoryId 和 name 查找 options
              this.brandQuery.id = null;
            }
          })
        }
      }
    }
  },
}
</script>
